﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
using System.Timers;
using System.Windows;
using System.ComponentModel;
using System.Windows.Threading;

namespace ClipboardEditor
{
    public class MainWindowViewModel : INotifyPropertyChanged
    {
        public MainWindowViewModel(Dispatcher d)
        {
            _dispatcher = d;
            _data = Clipboard.GetDataObject();
            _timer_Elapsed(null, null);

            _timer = new Timer(1000);
            _timer.Elapsed += new ElapsedEventHandler(_timer_Elapsed);
            _timer.AutoReset = true;
            _timer.Start();

        }

        Timer _timer;
        IDataObject _data;
        Dispatcher _dispatcher;


        public ObservableCollection<object> ClipboardItems { get; set; }

        void _timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            _dispatcher.Invoke(new Action(() =>
            {
                if (!Clipboard.IsCurrent(_data))
                { 
                    _data = Clipboard.GetDataObject();

                    ClipboardItems = new ObservableCollection<object>(_data.GetFormats());
                    OnPropertyChanged("ClipboardItems");
                }
            }), DispatcherPriority.Normal, null);
            
        }


        public void Dispose()
        {
            if (_timer != null)
                _timer.Dispose();
        }

        protected void OnPropertyChanged(string propertyName)
        {
            if(PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }

        public event PropertyChangedEventHandler PropertyChanged;
    }
}
